package com.atguigu.juc.cf;

import org.junit.jupiter.api.Test;

import java.util.concurrent.*;

/**
 * @author yanglin
 * @create 2023-12-29 11:19 星期五
 * description:
 */
public class CompletableFutureBuildDemo {
    
    @Test
    public void testCompletableFutureBuild() throws ExecutionException, InterruptedException {

        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        /**
         * 若指定了线程池，就使用指定线程池中的线程
         * 若未指定线程池，则使用ForkJoinPool.commonPool() 
         * CompletableFuture.runAsync()  无返回值
         */
//        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
//            System.out.println(Thread.currentThread().getName());
//            //暂停1秒钟
//            try {
//                TimeUnit.SECONDS.sleep(1);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        },threadPool);

        /**
         * 若指定了线程池，就使用指定线程池中的线程
         * 若未指定线程池，则使用ForkJoinPool.commonPool() 
         * CompletableFuture.supplyAsync()  有返回值
         */
        CompletableFuture<Object> objectCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            //暂停1秒钟
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello supplyAsync";
        },threadPool);

        threadPool.shutdown();
        
//        System.out.println(voidCompletableFuture.get());
        System.out.println(objectCompletableFuture.get());
    }
    
}
